// gcc demo_rtsql_c.c -lsqlite3 -std=c11 -o demo_for_c

#include "rtsql_c.hpp"

int main(int argc, char* argv[]){
    // 异常处理
    switch(setjmp(Sqlite3Except)){
        case 0:
            printf("Initialize...\n");
            break;
        case Decrypt_Err:
            printf("Wrong database passwd, try again.\n");
            exit(-2);
        default:
            printf("Except when exec sqlite3, exit.\n");
            exit(-1);
    }

    // 打开数据库
    sqlite3 *db = db_open_write("../test.db");

    // 加密数据库
    if(argc > 1){
        if(!strcmp(argv[1], "clear")){
            char strCipher[20] = {0};
            char strCipher_new[20] = {0};
            printf("Please Input the Origin Key -> ");
            scanf("%s", strCipher);
            printf("Please Input a New Key -> ");
            scanf("%s", strCipher_new);
            if(strcmp(strCipher_new, "null"))  // 更改密码
                db_setkey(db, strCipher, strCipher_new);
            else                               // 清除密码
                db_setkey(db, strCipher, "");
        }
        else if(!strcmp(argv[1], "encrypt")){
            // 给未加密数据库添加密码
            char strCipher[20] = {0};
            printf("Please Input the New Key -> ");
            scanf("%s", strCipher);
            db_setkey(db, "", strCipher);
        }
    }

    // 验证密码
    char strCipher[20] = {0};
    printf("Please Input the Cipher -> ");  scanf("%s", strCipher);
    if(strcmp(strCipher, "null"))
        db_unlock(db, strCipher);

    // 执行插入语句
    db_exec(db, "insert into tb1 values (256,'tmp','testing');", nullptr, nullptr);

    // 获取数据
    int row, column;
    char** pSelect = db_select(db, "select * from tb1;", &row, &column);

    // 注意，此处为 <= ，原因：row为数据行数，但pSelect包含了表头信息，元素数量为(raw+1)*column
    for(int i=0; i <= row; i++){
        for(int j=0; j < column; j++){
            printf("%s\t", pSelect[i*column + j]);
        }
        printf("\n");
    }
    select_free(pSelect);

    // 删除数据
    db_exec(db, "delete from tb1 where content='tmp';", nullptr, nullptr);

    // 关闭数据库
    db_close(db);
}
